<template>
  <el-dialog
    :model-value="modelValue"
    :title="title"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="counselor-form"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="标签" prop="tag">
        <el-input v-model="formData.tag" placeholder="请输入标签" />
      </el-form-item>

      <el-form-item label="工作地址" prop="workplace">
        <el-input v-model="formData.workplace" placeholder="请输入工作地址" />
      </el-form-item>
      <el-form-item label="咨询师等级" prop="level">
        <el-input v-model="formData.level" placeholder="请输入咨询师等级" />
      </el-form-item>
      <el-form-item label="心理咨询证书" prop="certificate">
        <el-input v-model="formData.certificate" placeholder="请输入心理咨询证书" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import counselorApi from '@/api/counselor'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    default: '新增咨询师'
  },
  form: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref(null)
const formData = ref({
  userId: '',
  name: '',
  mobile: '',
  email: '',
  gender: 1,
  tag: '',
  workplace: '',
  level: '',
  certificate: ''
})

// 监听外部表单数据变化
watch(() => props.form, (newVal) => {
  const { userId, ...rest } = newVal
  formData.value = {
    userId: '',
    name: '',
    mobile: '',
    email: '',
    gender: 1,
    tag: '',
    workplace: '',
    level: '',
    certificate: '',
    ...rest
  }
}, { deep: true, immediate: true })

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  tags: [
    { required: true, message: '请输入标签', trigger: 'blur' },
    { min: 1, max: 20, message: '标签长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  workplace: [
    { required: true, message: '请输入工作地址', trigger: 'blur' },
    { min: 1, max: 20, message: '工作地址长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请输入咨询师等级', trigger: 'blur' },
    { min: 1, max: 20, message: '咨询师等级长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  certificate: [
    { required: true, message: '请输入心理咨询证书', trigger: 'blur' },
    { min: 1, max: 20, message: '心理咨询证书长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

const handleClose = () => {
  emit('update:modelValue', false)
  formRef.value?.resetFields()
}

const handleConfirm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const { userId, ...submitData } = formData.value
        let res

        if (userId) {
          res = await counselorApi.updateCounselor(userId, {
            ...submitData,
            user_id: userId
          })
        } else {
          res = await counselorApi.createCounselor(submitData)
        }

        if (res) {
          ElMessage.success(userId ? '更新成功' : '创建成功')
          emit('success')
          handleClose()
        } else {
          ElMessage.error(res.data?.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.counselor-form {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 5px;
}
</style>
